package com.template.ejb.rest.bean;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.runtime.StatelessKnowledgeSession;

import com.template.ejb.rest.CalculatorResource;
import com.template.ejb.rest.dto.MathDTO;
import com.template.ejb.service.Calculator;
import com.template.ejb.service.util.JMSProducer;
import com.template.ejb.service.util.JbpmEngine;

/**
 * 
 * 
 */
@Stateless
public class CalculatorResourceBean implements CalculatorResource {

	private static final String QUEUE_CONNECTION_FACTORY = "ConnectionFactory";
	private static final String LONG_PROCESS_QUEUE = "queue/myQueue";

	@EJB
	private Calculator calculator;

	private JbpmEngine jbpmEngine = JbpmEngine.getInstance();
	
	/**
	 * 
	 */
	@Override
	public Long add(MathDTO value) {
		return calculator.add(value.getA(), value.getB());
	}

	/**
	 * 
	 */
	@Override
	public void message(MathDTO value) {
		JMSProducer jmsProducer = JMSProducer.getInstance();
		jmsProducer.sendMessage(value,
				CalculatorResourceBean.QUEUE_CONNECTION_FACTORY,
				CalculatorResourceBean.LONG_PROCESS_QUEUE);
		
	}

	/**
	 * 
	 */
	@Override
	public void execute(String value) {
		jbpmEngine
				.deployFromClasspath("com/template/bpm/processdefinition.jpdl.xml");
		jbpmEngine.startByKey("processdefinition");
	}
	
	@Override
	public void rule(){

		KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
		
		KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
		
		kbuilder.add( ResourceFactory.newClassPathResource( "licenseApplication.drl", getClass() ),
		              ResourceType.DRL );
		
		if ( kbuilder.hasErrors() ) {
		    System.err.println( kbuilder.getErrors().toString() );
		}
		
		kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
		
		////
		
		StatelessKnowledgeSession ksession = kbase.newStatelessKnowledgeSession();
		Applicant applicant = new Applicant( "Mr John Smith", 19 );
		ksession.execute( applicant );

		System.out.println("******** IsValid: " + applicant.isValid());
		
	}

}
